/* 请求的错误不应该被调用方被catch
   把错误的请求当成请求正常返回的结果
   由调用方根据状态码来判断是否成功 */
var base64 = require('/base64');
const app = getApp();
const config = require('../config/config.js');


/* 服务端IP+端口 */
// export const API_URI = config.server_add+':'+config.
export const API_URI = config.server_add + config.server_port


/* 调用的请求方法 */
function request(url, requestType, params) { 
  return new Promise((resolve, reject) => {
    wxRequest(url, requestType, params).then(res => {
      // console.log('[请求地址]：', url, 
      //             '\n[请求参数]：', params, 
      //             '\n[响应状态]：', res.data.code, 
      //             '\n[响应数据]：', res.data.data, 
      //             '\n[响应信息]：', res.data.message,
      //             '\n[异常信息]：', res.data.exception )
      switch (res.data.code) {
        case 200:
          break;
        case 99999: case 301://99999 数据重复 到各自的前台页面去处理 2022年11月14日  301 该报价单已经在集团商城(酷家乐设计完成)下单 到各自的前台页面去处理
          break;
        case 404:
          if (url == '/login') {
            wx.navigateTo({
              url: '/pages/grant/grant',
            })
          }
           break
        case -2:case -4:case 233:
          wx.showModal({ title: '提示', content: '请先授权登录', showCancel: false,
          success: function (res) {
            // wx.navigateTo({
            //   url: '/pages/grant/grant',
            // })
              }
           });
        break;
        default:
          if (res.data.exception){
            wx.showModal({
              title: '提示', content: res.data.msg, cancelText: '日志',
              success(res_model) {
                if (res_model.cancel) {
                  wx.showModal({ title: '异常信息', content: res.data.exception, showCancel: false });
                }
              }
            });
          }else{
            wx.showModal({ title: '提示', content: res.data.msg, showCancel: false });
          }
          break;
      }
      resolve(res)
    }).catch(err => {
      resolve({ code: -200, message: "请求失败", data: err });
    })
  })
}

/* 封装wx.request */
function wxRequest(url, requestType, params) {
  return new Promise((resolve, reject) => {
    let app = getApp(), header = {
      'content-type': 'application/json'
    }
    var openId =app.globalData.open_id
    if (app.globalData.user) {
      app.globalData.user.openId = openId 
      header['Authorization'] = "Bearer "+app.globalData.token
    }
    if (app.globalData.customerInfo) {
      app.globalData.customerInfo.openId = openId

      header['Authorization'] = base64.encode(JSON.stringify(app.globalData.customerInfo)) 
    }

    wx.request({
      url: `${API_URI}/${url}`,
      header: header,
      data: params ? params : null,
      method: requestType ? requestType : 'POST',
      success: function (res) {
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  })
}

var loginApi = {
  async wxMiniAppLogin(phone) {
    await new Promise((resolve,reject)=>{
      wx.login({
        success: res => {
          var url = 'login'
          var data = {
            code: res.code,
          }
          request(url, 'POST', data).then(res => {
            console.log(res)
            if (res.data.code == 200) {
              wx.setStorageSync('user', res.data.data)
              resolve(res.data)
            }
          })
        }
      })
    })
},
cache(key, data) {

  if (data == undefined) {

    return wx.getStorageSync(key) || ''
  }

  wx.setStorageSync(key, data)
},
}
/* 暴露方法给外部 */
module.exports = {
  request,
  loginApi
}
